<template>
  <a-table
    :data="tableData"
    ref="tableRef"
    :bordered="{
      headerCell: true,
    }"
    :stripe="true"
  >
    <template #columns>
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>

      <a-table-column
        :width="150"
        data-index="produceLineId"
        title="资源配置"
        align="center"
      >
        <template #cell="{ record, rowIndex }">
          <div>
            {{ record.produceLineId ? record.produceLineName : '请选择资源配置'
            }}<icon-edit
              @click="
                refDrawerResources.setData(
                  rowIndex,
                  record.resourceType,
                  record.produceLineId
                )
              "
              :size="18"
              style="color: #096dd9; margin-left: 20px; cursor: pointer"
            />
          </div>
        </template>
      </a-table-column>
      <a-table-column
        :width="150"
        data-index="supervisor"
        title="生产主管"
        align="center"
      >
        <template #cell="{ record }">
          {{ mock.filter((ele) => ele.id === record.supervisor)[0].name }}
        </template>
      </a-table-column>
      <a-table-column
        :width="150"
        data-index="schedulingNumbering"
        title="已排程数量"
        align="center"
      >
      </a-table-column>
      <a-table-column
        :width="150"
        data-index="awaitSchedulingNumber"
        title="待排程数量"
        align="center"
      >
        <template #cell="{ record }">
          {{ record.awaitSchedulingNumber }}
        </template>
      </a-table-column>
      <a-table-column
        :width="150"
        data-index="schedulingNumber"
        title="排程数量"
        align="center"
      >
        <template #title>
          <div class="title_before">排程数量</div>
        </template>
        <template #cell="{ record }">
          <a-input-number
            :min="1"
            @change="calculate"
            :max="data.workShopPlanName"
            v-model="record.schedulingNumber"
          />
        </template>
      </a-table-column>
      <a-table-column
        :width="150"
        data-index="planBeginAt"
        title="计划开工时间"
        align="center"
      >
        <template #cell="{ record, rowIndex }">
          <a-date-picker
            @change="changePlanDuration(rowIndex)"
            value-format="timestamp"
            v-model="record.planBeginAt"
            show-time
            format="YYYY-MM-DD HH:mm"
          />
        </template>
      </a-table-column>
      <a-table-column
        :width="150"
        data-index="planTime"
        title="计划工作时长"
        align="center"
      >
        <!-- <template #cell="{ record }">
          <a-input-number :min="1" v-model="record.planTime" />
        </template> -->
      </a-table-column>
      <a-table-column
        :width="150"
        data-index="planEndAt"
        title="计划完工时间"
        align="center"
      >
        <template #cell="{ record, rowIndex }">
          <a-date-picker
            @change="changePlanDuration(rowIndex)"
            value-format="timestamp"
            v-model="record.planEndAt"
            show-time
            format="YYYY-MM-DD HH:mm"
          />
        </template>
      </a-table-column>
      <a-table-column :width="150" fixed="right" title="操作" align="center">
        <template #cell="{ rowIndex }">
          <a-button
            v-if="rowIndex === 0"
            @click="controls(rowIndex)"
            type="outline"
          >
            拆分
          </a-button>
          <a-button
            v-else
            @click="controls(rowIndex)"
            type="outline"
            status="danger"
          >
            删除
          </a-button>
        </template>
      </a-table-column>
    </template>
  </a-table>
  <DrawerResources @handleOk="selectResource" ref="refDrawerResources" />
</template>

<script setup lang="ts">
  import { reactive, ref, onMounted, computed, watch } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { cloneDeep } from 'lodash';
  import DrawerResources from './DrawerResources.vue';

  let refDrawerResources = ref();
  interface TtableData {
    schedulingId?: number; //所属排程id
    produceLineId?: number; // 所属产线id
    schedulingNumbering: number; // 已排程数量
    schedulingNumber: number; // 排程数量
    awaitSchedulingNumber: number; // 待排程数量
    planBeginAt?: number; // 计划开工时间
    planEndAt?: number; // 计划完工时间
    planTime?: number; // 计划工作时长
    supervisor?: number; // 生产主管
    resourceType?: number; // 资源类型
    produceLineName?: string; // 所属产线名字
  }
  const data = reactive(
    JSON.parse(localStorage.getItem('ManualSchedulingForm') as string)
  );
  onMounted(() => {
    let data = JSON.parse(
      localStorage.getItem('ManualSchedulingForm') as string
    );
    refDrawerResources.value.setWorkShopAndProcessGroup(
      data?.workShopId,
      data?.processGroupId
    );
  });

  const tableData = reactive<TtableData[]>([
    {
      schedulingId: data.id,
      produceLineId: 0,
      schedulingNumbering: 0,
      schedulingNumber: 0,
      awaitSchedulingNumber: data.workShopPlanName,
      planBeginAt: undefined,
      planEndAt: undefined,
      planTime: 0,
      supervisor: 2,
      produceLineName: '',
    },
  ]);
  const selectResource = (selectData: {
    index: number;
    resourceType: number;
    choiceId: number;
    choiceName: string;
  }) => {
    tableData[selectData.index].produceLineId = selectData.choiceId;
    tableData[selectData.index].produceLineName = selectData.choiceName;
    tableData[selectData.index].resourceType = selectData.resourceType;
  };
  // 拆分与分解
  const controls = (index: number) => {
    if (index) {
      tableData.splice(index, 1);
      return;
    }
    tableData.push({
      schedulingId: data.id,
      produceLineId: 0,
      schedulingNumbering: 0,
      schedulingNumber: 0,
      awaitSchedulingNumber:
        tableData[tableData.length - 1].awaitSchedulingNumber,
      planBeginAt: undefined,
      planEndAt: undefined,
      planTime: 0,
      supervisor: 2,
    });
  };
  // 计算函数
  const calculate = () => {
    let sum = 0;
    tableData.forEach((ele, index) => {
      if (!index) {
        sum += ele.schedulingNumber;
        ele.awaitSchedulingNumber = data.workShopPlanName - sum;
        ele.schedulingNumbering = ele.schedulingNumber;
      } else {
        sum += ele.schedulingNumber;
        ele.schedulingNumbering = ele.schedulingNumber;
        ele.awaitSchedulingNumber = data.workShopPlanName - sum;
      }
    });
  };

  const mock = [
    {
      id: 1,
      name: '主管A',
    },
    {
      id: 2,
      name: '主管B',
    },
    {
      id: 3,
      name: '主管C',
    },
    {
      id: 4,
      name: '主管D',
    },
  ];
  const changePlanDuration = (index: number) => {
    const beginTime = tableData[index].planBeginAt as number;
    const endTime = tableData[index].planEndAt as number;
    if (endTime && beginTime && beginTime <= endTime) {
      const millisecondsPerHour = 3600000; // 1小时等于3600秒 * 1000毫秒
      const timeDifference = Math.abs(endTime - beginTime); // 获取时间戳的差值
      const hoursDifference = timeDifference / millisecondsPerHour; // 将差值转换为小时
      tableData[index].planTime = Math.floor(hoursDifference);
    } else if (beginTime > endTime) {
      Message.error('开始时间大于结束时间');
    }
  };
  defineExpose({ tableData });
</script>

<style lang="less" scoped>
  .title_before {
    position: relative;
  }
  .title_before::before {
    content: '*';
    color: red;
    font-size: 16px;
  }
  :deep(.arco-table-tr) {
    height: 40px;
  }
  :deep(.arco-table-th) {
    font-weight: bold;
    // font-size: 13px;
  }
</style>
